package io.esirong.widget;

import android.app.Activity;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Build;
import android.view.Display;
import android.view.View;
import android.view.ViewTreeObserver;

/**
 * 适用：处理健盘遮盖，遮挡view 需要动态的移动。显示View的位置避开输入健盘的遮挡，遮盖。
 * 使用
 */
public class FloatViewUtil {
    private static int height = 0;
    private final Activity mContext;
    private ViewTreeObserver.OnGlobalLayoutListener listener;
    private View root;

    public FloatViewUtil(Activity mContext) {
        this.mContext = mContext;
        if (height == 0) {
            Display defaultDisplay = mContext.getWindowManager().getDefaultDisplay();
            Point point = new Point();
            defaultDisplay.getSize(point);
            height = point.y;
        }
    }

    /**
     * @param root      视图根节点
     * @param floatView float view 需要显示在键盘上的View组件
     */
    public void setFloatView(View root, View floatView) {
        this.root = root; //视图根节点 float view // 需要显示在键盘上的View组件
        listener = new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int[] location = new int[2];
                floatView.getLocationOnScreen(location);
                int viewHeight = floatView.getHeight();

                Rect r = new Rect();
                mContext.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                int heightDifference = height - (r.bottom);
                boolean isKeyboardShowing = heightDifference > height / 3;
                if (isKeyboardShowing) {
                    //元素屏幕位置 减去  窗口底部位置，计算出 当前屏幕中元素和 软键盘上方距离即可
                    int ty = location[1] + viewHeight - r.bottom;
                    if (ty <= 0) {
                        return;
                    }
                    floatView.animate().translationY(-ty).setDuration(0).start();
                } else {
                    floatView.animate().translationY(0).start();
                }
            }
        };
        root.getViewTreeObserver().addOnGlobalLayoutListener(listener);
    }


    public void clearFloatView() {
        if (listener != null && root != null)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                root.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
            } else {
                root.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
            }
    }

}
